package com.mavenq.fly.business.controller;

import com.mavenq.fly.business.PersonService;
import com.mavenq.fly.business.entity.OperationLog;
import com.mavenq.fly.business.vo.Person;
import com.mavenq.fly.commons.exception.BusinessException;
import com.mavenq.fly.commons.resp.ResponseBuilder;
import com.mavenq.fly.commons.resp.ResponseObj;
import com.mavenq.fly.commons.tools.SpringBeanFactory;
import com.mavenq.fly.config.UploadProperties;
import com.mavenq.fly.listener.PushEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/person")
@Slf4j
public class PersonController {

    @Autowired
    private PersonService personService;
    @Autowired
    private UploadProperties uploadProperties;

    @RequestMapping("/list/{familyId}")
    public ResponseObj getPersonList(@PathVariable String familyId) throws Exception {

        log.info("输入参数：familyId={}",familyId);

        if(StringUtils.endsWithIgnoreCase(familyId,"0")){
            log.error("参数结尾不能为0");
            throw new RuntimeException("参数结尾不能为0");
        }
        if(StringUtils.endsWithIgnoreCase(familyId,"1")){
            log.error("参数结尾不能为1");
            throw new BusinessException(400,"参数结尾不能为1");
        }
        log.warn("upload下载参数: {}", uploadProperties.getFileMap());
        return personService.getPersonList(Long.parseLong(familyId));
    }

    @RequestMapping("publish")
    public ResponseObj pushEvent(){
        List<String> names = new ArrayList<>();
        names.add("chupengfei");
        ApplicationContext ctx = SpringBeanFactory.getCtx();
        ApplicationEvent event = new PushEvent<>(names, 2);
        ctx.publishEvent(event);
        return ResponseBuilder.buildSuccess("succ");
    }

    @PostMapping("save")
    public ResponseObj save(@Valid @RequestBody Person person){
//        log.info("update ...");
//        person.setAge(11);
//        person.setName("sb");
        return ResponseBuilder.buildSuccess(person);
    }

    @PostMapping("hello")
    public ResponseObj requestBody(@RequestBody Person person){

        return ResponseBuilder.buildSuccess(person);
    }

    @PostMapping("testSpringContext")
    public ResponseObj testSpringContext() throws InterruptedException {
        List<OperationLog> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Person person1 = new Person();
            person1.setId((long)i+1);
            list.add(person1.exec());
        }

        return ResponseBuilder.buildSuccess(list);
    }

}
